package edu.unlv.cs.ladders.web;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import edu.unlv.cs.ladders.entities.Tag;
import edu.unlv.cs.ladders.entities.Tournament;
import edu.unlv.cs.ladders.services.PermissionService;

import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;

@RequestMapping("/tag/**")
@Controller
public class TagController {
	@PreAuthorize("hasRole('ROLE_PARTICIPANT')")
    @RequestMapping(value = "/tag", method = RequestMethod.POST)
    public String create(@Valid Tag tag, BindingResult result, ModelMap modelMap) {
        if (tag == null) throw new IllegalArgumentException("A tag is required");
        if (result.hasErrors()) {
            modelMap.addAttribute("tag", tag);
            modelMap.addAttribute("tournaments", Tournament.findAllTournaments());
            return "tag/create";
        }
        tag.persist();
        for(Tournament tournament : tag.getTournaments()){
        	tournament.addTag(tag);
        }
        this.getPermissionService().setDefaultPermissions(tag);
        return "redirect:/tag/" + tag.getId();
    }

	@PreAuthorize("hasRole('ROLE_PARTICIPANT')")
    @RequestMapping(value = "/tag/form", method = RequestMethod.GET)
    public String createForm(ModelMap modelMap) {
        modelMap.addAttribute("tag", new Tag());
        modelMap.addAttribute("tournaments", Tournament.findAllTournaments());
        return "tag/create";
    }
    
    @RequestMapping(value = "/tag/{id}", method = RequestMethod.GET)
    public String show(@PathVariable("id") Long id, ModelMap modelMap) {
        if (id == null) throw new IllegalArgumentException("An Identifier is required");
        modelMap.addAttribute("tag", Tag.findTag(id));
        return "tag/show";
    }
    
    @RequestMapping(value = "/tag", method = RequestMethod.GET)
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, ModelMap modelMap) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            modelMap.addAttribute("tags", Tag.findTagEntries(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));
            float nrOfPages = (float) Tag.countTags() / sizeNo;
            modelMap.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            modelMap.addAttribute("tags", Tag.findAllTags());
        }
        return "tag/list";
    }
    
    @PreAuthorize("hasPermission(#tag,'write') or hasRole('ROLE_COORDINATOR')")
    @RequestMapping(method = RequestMethod.PUT)
    public String update(@Valid Tag tag, BindingResult result, ModelMap modelMap) {
        if (tag == null) throw new IllegalArgumentException("A tag is required");
        if (result.hasErrors()) {
            modelMap.addAttribute("tag", tag);
            modelMap.addAttribute("tournaments", Tournament.findAllTournaments());
            return "tag/update";
        }
        tag.merge();
        return "redirect:/tag/" + tag.getId();
    }

    @PreAuthorize("hasPermission(#id,'edu.unlv.cs.ladders.entities.Tag','write') or hasRole('ROLE_COORDINATOR')")
    @RequestMapping(value = "/tag/{id}/form", method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") Long id, ModelMap modelMap) {
        if (id == null) throw new IllegalArgumentException("An Identifier is required");
        modelMap.addAttribute("tag", Tag.findTag(id));
        modelMap.addAttribute("tournaments", Tournament.findAllTournaments());
        return "tag/update";
    }
    
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @RequestMapping(value = "/tag/{id}", method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size) {
        if (id == null) throw new IllegalArgumentException("An Identifier is required");
        Tag.findTag(id).remove();
        return "redirect:/tag?page=" + ((page == null) ? "1" : page.toString()) + "&size=" + ((size == null) ? "10" : size.toString());
    }
    
    @RequestMapping(value = "find/ByName/form", method = RequestMethod.GET)
    public String findTagsByNameForm(ModelMap modelMap) {
        return "tag/findTagsByName";
    }
    
    @RequestMapping(value = "find/ByName", method = RequestMethod.GET)
    public String findTagsByName(@RequestParam("name") String name, ModelMap modelMap) {
        if (name == null || name.length() == 0) throw new IllegalArgumentException("A Name is required.");
        modelMap.addAttribute("tags", Tag.findTagsByName(name).getResultList());
        return "tag/list";
    }
    
	private PermissionService permissionService;
	@Autowired
	public void setPermissionService(PermissionService permissionService) {
		this.permissionService = permissionService;
	}
	public PermissionService getPermissionService() {
		return permissionService;
	}

}
